package com.ku.boobs;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity{
	Button takePicture;
	Button sendPicture;
	Button facebook;
	Button twitter;
	Button website;
	Button developer;
	Button pickImage;
	Button pickOverlay;
	Button rotateImage;
	ImageView iv;
	String TAG = "KUBOOBS";
	Bitmap bitmap;
	int SELECT_PIC_REQUEST = 1;
	int CAMERA_PIC_REQUEST = 2;
	Uri uri;
	Uri photoUri;
	Uri emailUri;
	int boobnum = 100000;
	InputStream in = null;
    FileOutputStream fo;
    File folder;
    File f;
    String[] emailstring= {"submit@kuboobs.com"};
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
    Date now = new Date();
    String filename = formatter.format(now);
    String emailFilename = "";
    int overlay = R.drawable.kuboobs;
    float rotateDegree = 0;
    float rotateCamera = 0;
    final CharSequence[] items = {"#KUBOOBS", "Jayhawk", "Ribbon", "Android", "Chrome"};
    
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    rotateCamera = sp.getFloat("rotated", rotateCamera);
    overlay = sp.getInt("overlay", overlay);
    
    iv = (ImageView) findViewById(R.id.imageView1);
    
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	builder.setTitle("Choose overlay.");
	builder.setItems(items, new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int item) {
	        switch(item)
	        {
	        	case 0:
	        	overlay = R.drawable.kuboobs;
	        	saveoverlay("overlay", overlay);
	        	break;	        	
	        	case 1:
	        	overlay = R.drawable.kubird;
	        	saveoverlay("overlay", overlay);
	        	break;	        	
	        	case 2:
		        overlay = R.drawable.breastcancer;
		        saveoverlay("overlay", overlay);
	        	break;	        	
	        	case 3:
	        	overlay = R.drawable.android;
	        	saveoverlay("overlay", overlay);
	        	break;
	        	case 4:
	        	overlay = R.drawable.chrome;
	        	saveoverlay("overlay", overlay);
	        	break;
	        }
	    }
	});
    
    createfolder();
    
	takePicture =(Button) findViewById(R.id.takeImage);
    takePicture.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
        	Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
        	cameraIntent.putExtra("return-data", true);
        	photoUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Pictures/KUBOOBS", "temp.png"));
        	cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);        
        	startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
        }
    });
    
    pickImage =(Button) findViewById(R.id.pickImage);
    pickImage.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
        	Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent = Intent.createChooser(intent, "Select image: ");
            startActivityForResult(intent,  SELECT_PIC_REQUEST);
        }
    });
    
    rotateImage = (Button) findViewById(R.id.rotateImage);
    rotateImage.setOnClickListener(new OnClickListener (){
    	@Override
        public void onClick(View view)
        {
    		if(uri != null)
        	{
	        	rotateDegree = rotateDegree + 90;
	        	if(rotateDegree > 270)
	        	{
	        		rotateDegree = 0;
	        	}
	        		getBitmapFromGallery();
        	}
    		else
        	{
        		Toast.makeText(getApplicationContext(), "Unable to rotate image.", Toast.LENGTH_SHORT).show();
        	}
        }
    });
    
    pickOverlay =(Button) findViewById(R.id.pickOverlay);
    pickOverlay.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View v)
        {
        	AlertDialog alert = builder.create();
        	alert.show();
        }
    });
    
    sendPicture =(Button) findViewById(R.id.submitImage);
    sendPicture.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
        	if(uri != null)
        	{
        		Intent emailIntent1 = new Intent(android.content.Intent.ACTION_SEND);
            	emailIntent1.setType("image/png");
            	emailIntent1.putExtra(Intent.EXTRA_EMAIL, emailstring);
                emailIntent1.putExtra(Intent.EXTRA_SUBJECT, "#KUBOOBS");
                File image = new File(folder, emailFilename);
                Uri pngUri = Uri.fromFile(image);
                emailIntent1.putExtra(android.content.Intent.EXTRA_STREAM, pngUri);
            	startActivity(emailIntent1);
        	}
        	else
        	{
        		Toast.makeText(getApplicationContext(), "Unable to get image.", Toast.LENGTH_SHORT).show();
        	}
        }	
    });
    
    facebook =(Button) findViewById(R.id.facebook);
    facebook.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
        	String url = "http://www.fb.com/kuboobs";
        	Intent i = new Intent(Intent.ACTION_VIEW);
        	i.setData(Uri.parse(url));
        	startActivity(i);
        }
    });
    
    twitter =(Button) findViewById(R.id.twitter);
    twitter.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
        	String url = "http://www.twitter.com/kuboobs";
        	Intent i = new Intent(Intent.ACTION_VIEW);
        	i.setData(Uri.parse(url));
        	startActivity(i);
        }
    });
    
    website =(Button) findViewById(R.id.website);
    website.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
        	String url = "http://www.kuboobs.com";
        	Intent i = new Intent(Intent.ACTION_VIEW);
        	i.setData(Uri.parse(url));
        	startActivity(i);
        }
    });
    
    developer =(Button) findViewById(R.id.developer);
    developer.setOnClickListener(new OnClickListener (){
        @Override
        public void onClick(View view)
        {
        	Intent i = new Intent(MainActivity.this, Developer.class);
            startActivity(i);
        }
    });
}

public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId())
    {
    case R.id.item1:
    	rotateCamera = 0;
    	saveprefs("rotated",0);
        Toast.makeText(MainActivity.this, "Camera images will not rotate.", Toast.LENGTH_SHORT).show();
    	break;
    case R.id.item2:
    	rotateCamera = 90;
    	saveprefs("rotated",90);
        Toast.makeText(MainActivity.this, "Camera images will rotate 90 degrees.", Toast.LENGTH_SHORT).show();
    	break;
    case R.id.item3:
    	rotateCamera = 180;
    	saveprefs("rotated",180);
        Toast.makeText(MainActivity.this, "Camera images will rotate 180 degrees.", Toast.LENGTH_SHORT).show();
    	break;
    case R.id.item4:
    	rotateCamera = 270;
    	saveprefs("rotated",270);
        Toast.makeText(MainActivity.this, "Camera images will rotate 270 degrees.", Toast.LENGTH_SHORT).show();
    	break;
    }
        return true;
}

private void saveprefs(String key, float value)
{
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        Editor edit = sp.edit();
        edit.putFloat(key, value);
        edit.commit();
}

private void saveoverlay(String key, int overlay)
{
	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit = sp.edit();
    edit.putInt(key, overlay);
    edit.commit();	
}

void createfolder()
{
	folder = new File(Environment.getExternalStorageDirectory() + "/Pictures/KUBOOBS");
    boolean success = false;
    if(!folder.exists()){
        success = folder.mkdirs();
    }
    if (!success){ 
        Log.d(TAG,"Folder not created.");
    }
    else{
        Log.d(TAG,"Folder created!");
    }
}

public Bitmap getBitmapFromGallery() {

	in = null;
	f = null;
	emailUri = null;
	if(bitmap != null)
	{
		bitmap = null;
		bitmap.recycle();
		System.gc();
	}
	try {
	    final int IMAGE_MAX_SIZE = 600000; //1200000 = 1.2MP
	    ContentResolver mContentResolver = getContentResolver();
	    in = mContentResolver.openInputStream(uri);

	    // Decode image size
	    BitmapFactory.Options o = new BitmapFactory.Options();
	    o.inJustDecodeBounds = true;
	    BitmapFactory.decodeStream(in, null, o);
	    in.close();    
	    int scale = 1;
	    while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
	          IMAGE_MAX_SIZE) {
	       scale++;
	    }
	    Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

	    Bitmap bitmap = null;
	    in = mContentResolver.openInputStream(uri);
        // scale to max possible inSampleSize that still yields an image
        // larger than target
        o = new BitmapFactory.Options();
        o.inSampleSize = scale;
        bitmap = BitmapFactory.decodeStream(in, null, o);

        Matrix m = new Matrix();
        m.postRotate(rotateDegree);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, o.outWidth, o.outHeight, m, true);

        // resize to desired dimensions
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        Log.d(TAG, "1th scale operation dimenions - width: " + width + ", height: " + height);

        double y = 612;
        double x = 612;

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(rotatedBitmap, (int) x, (int) y, true);
        Bitmap overlayBitmap;
        Canvas c = new Canvas(scaledBitmap);
        Resources res = getResources();
        overlayBitmap  = BitmapFactory.decodeResource(res, overlay); //overlay  
        Drawable drawable1 = new BitmapDrawable(scaledBitmap);
        Drawable drawable2 = new BitmapDrawable(overlayBitmap);
        drawable1.setBounds(0, 0, (int) x, (int) y);
        drawable2.setBounds(0, 0, (int) x, (int) y);
        drawable1.draw(c);
        drawable2.draw(c);
        bitmap.recycle();
        bitmap = scaledBitmap;
        System.gc();
	    in.close();
	    folder = new File(Environment.getExternalStorageDirectory() + "/Pictures/KUBOOBS");
        boolean success2 = false;
        if(!folder.exists()){
            success2 = folder.mkdirs();
        }
        if (!success2){ 
            Log.d(TAG,"Folder not created.");
        }
        else{
            Log.d(TAG,"Folder created!");
        }
        ByteArrayOutputStream bytes2 = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes2);
        //you can create a new file name "test.png" in sdcard folder.
        f = new File(folder+"/"+"KUBOOBS"+filename+".png");
        emailFilename = "KUBOOBS"+filename+".png";
        emailUri = Uri.fromFile(f);
        if(f.exists())
        {
        	f = new File(folder+"/"+"KUBOOBS_"+filename+".png");
        	emailFilename = "KUBOOBS_"+filename+".png";
        	if(f.exists())
        	{
        		f = new File(folder+"/"+"_KUBOOBS_"+filename+".png");
        		emailFilename = "_KUBOOBS_"+filename+".png";
        	}
        }
        try {
                f.createNewFile();
        } catch (IOException e) {
                e.printStackTrace();
        }
        //write the bytes in file
        try {
                fo = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        }
        try {
                fo.write(bytes2.toByteArray());
        } catch (IOException e) {
                e.printStackTrace();
        }
        // remember close the FileOutput
        try {
                fo.close();
        } catch (IOException e) {
                e.printStackTrace();
        }
        File delete = new File(Environment.getExternalStorageDirectory() + "/Pictures/KUBOOBS", "temp.png");
        delete.delete();
		iv.setImageBitmap(bitmap);
	    return bitmap;
	} catch (IOException e) {
	    Log.e(TAG, e.getMessage(),e);
	    return null;
	}
}

public Bitmap getBitmapFromCamera() {
	in = null;
	f = null;
	emailUri = null;
	if(bitmap != null)
	{
		bitmap = null;
		bitmap.recycle();
		System.gc();
	}
	try {
	    final int IMAGE_MAX_SIZE = 600000; //1200000 = 1.2MP
	    ContentResolver mContentResolver = getContentResolver();
	    in = mContentResolver.openInputStream(uri);
	    // Decode image size
	    BitmapFactory.Options o = new BitmapFactory.Options();
	    o.inJustDecodeBounds = true;
	    BitmapFactory.decodeStream(in, null, o);
	    in.close();    
	    int scale = 1;
	    while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
	          IMAGE_MAX_SIZE) {
	       scale++;
	    }
	    Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
	    Bitmap bitmap = null;
	    in = mContentResolver.openInputStream(uri);
        // scale to max possible inSampleSize that still yields an image
        // larger than target
        o = new BitmapFactory.Options();
        o.inSampleSize = scale;
        bitmap = BitmapFactory.decodeStream(in, null, o);
        
        Matrix rotate = new Matrix();
        rotate.preRotate(rotateCamera);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, o.outWidth, o.outHeight, rotate, true);
        
        // resize to desired dimensions
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        Log.d(TAG, "1th scale operation dimenions - width: " + width + ", height: " + height);
        double y = 612;
        double x = 612;
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(rotatedBitmap, (int) x, (int) y, true);
        Bitmap overlayBitmap;
        Canvas c = new Canvas(scaledBitmap);
        Resources res = getResources();
        overlayBitmap  = BitmapFactory.decodeResource(res, overlay); //overlay
        Drawable drawable1 = new BitmapDrawable(scaledBitmap);
        Drawable drawable2 = new BitmapDrawable(overlayBitmap);
        drawable1.setBounds(0, 0, (int) x, (int) y);
        drawable2.setBounds(0, 0, (int) x, (int) y);
        drawable1.draw(c);
        drawable2.draw(c);
        bitmap.recycle();
        bitmap = scaledBitmap;
        System.gc();
	    in.close();
		folder = new File(Environment.getExternalStorageDirectory() + "/Pictures/KUBOOBS");
        boolean success2 = false;
        if(!folder.exists()){
            success2 = folder.mkdirs();
        }
        if (!success2){ 
            Log.d(TAG,"Folder not created.");
        }
        else{
            Log.d(TAG,"Folder created!");
        }
        ByteArrayOutputStream bytes2 = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes2);
        //you can create a new file name "test.png" in sdcard folder.
        f = new File(folder+"/"+"KUBOOBS"+filename+".png");
        emailFilename = "KUBOOBS"+filename+".png";
        emailUri = Uri.fromFile(f);
        if(f.exists())
        {
        	f = new File(folder+"/"+"KUBOOBS_"+filename+".png");
        	emailFilename = "KUBOOBS_"+filename+".png";
        	if(f.exists())
        	{
        		f = new File(folder+"/"+"_KUBOOBS_"+filename+".png");
        		emailFilename = "KUBOOBS_"+filename+"2"+".png";
        	}
        }
        try {
                f.createNewFile();
        } catch (IOException e) {
                e.printStackTrace();
        }
        //write the bytes in file
        try {
                fo = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        }
        try {
                fo.write(bytes2.toByteArray());
        } catch (IOException e) {
                e.printStackTrace();
        }
        // remember close the FileOutput
        try {
                fo.close();
        } catch (IOException e) {
                e.printStackTrace();
        }
        File delete = new File(Environment.getExternalStorageDirectory() + "/Pictures/KUBOOBS", "temp.png");
        delete.delete();
		iv.setImageBitmap(bitmap);
	    return bitmap;
	} catch (IOException e) {
	    Log.e(TAG, e.getMessage(),e);
	    return null;
	}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
	super.onActivityResult(requestCode, resultCode, data);
	
		if( resultCode == RESULT_OK)
			{
				if(requestCode == CAMERA_PIC_REQUEST)
				{
					uri = photoUri;
					getBitmapFromCamera();
				}
				else if(requestCode == SELECT_PIC_REQUEST)
				{
					uri = Uri.parse(data.getDataString());
					getBitmapFromGallery();
				}
			else 
			{
				Toast.makeText(MainActivity.this, "Could not get picture.", Toast.LENGTH_LONG).show();
			}
		super.onActivityResult(requestCode, resultCode, data);
		}
}
}